package the.workshop.milktea.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.wisteria.framework.web.QueryResult;
import org.wisteria.framework.web.mvc.dto.ConditionDTO;
import org.wisteria.framework.web.mvc.service.AbstractSuperService;
import the.workshop.milktea.infrastructure.mapper.FirmwareMapper;
import the.workshop.milktea.infrastructure.model.Firmware;
import the.workshop.milktea.service.dto.FirmwareAddDTO;
import the.workshop.milktea.service.dto.FirmwareGetDTO;
import the.workshop.milktea.service.dto.FirmwareModifyDTO;
import the.workshop.milktea.service.dto.FirmwarePageDTO;

@Service
public class FirmwareService extends AbstractSuperService<FirmwareMapper, Firmware> {

    public boolean add(FirmwareAddDTO dto) {
        Firmware firmware = new Firmware();
        firmware.setName(dto.getName());
        firmware.setContent(dto.getContent());
        firmware.setDownloadAddress(dto.getDownloadAddress());
        firmware.setVersion(dto.getVersion());
        firmware.setUpdateTime(dto.getUpdateTime());
        this.baseMapper.insert(firmware);
        return true;
    }

    public boolean modify(FirmwareModifyDTO dto) {
        Firmware firmware = new Firmware();
        firmware.setId(dto.getFirmwareId());
        firmware.setName(dto.getName());
        firmware.setContent(dto.getContent());
        firmware.setDownloadAddress(dto.getDownloadAddress());
        firmware.setVersion(dto.getVersion());
        firmware.setUpdateTime(dto.getUpdateTime());
        this.baseMapper.updateById(firmware);
        return true;
    }

    /**
     * 分页查询
     *
     * @param condition 查询条件
     * @param pageNum   页码
     * @param pageSize  每页条数
     * @return
     */
    public QueryResult<FirmwareGetDTO> page(FirmwarePageDTO condition, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        Page<Firmware> page = this.baseMapper.selectListPage(condition);
        return new QueryResult(page.getTotal(), page.getResult());
    }

    public FirmwareGetDTO get(Integer id) {
        Firmware firmware = this.baseMapper.selectById(id);
        return firmware == null ? null : convertOf(firmware);
    }

    private FirmwareGetDTO convertOf(Firmware source) {
        FirmwareGetDTO target = new FirmwareGetDTO();
        BeanUtils.copyProperties(source, target);
        target.setFirmwareId(source.getId());
        return target;
    }

}
